package com.fast.common.controller;


import cn.hutool.core.bean.BeanUtil;
import com.fast.common.result.ApiHelper;
import com.fast.common.result.ApiResult;
import com.fast.common.service.IBaseService;
import com.google.common.base.CaseFormat;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * @Auther: lhy
 * @Date: 2021/11/11 12:49
 * @Mail: 190643201@qq.com
 */
@RestController
public class BaseApiController<S extends IBaseService<T>, T, P> {


    protected S service;

    protected String separator = ",";


    public ApiResult add(P param) {
        service.add(param);
        return ApiHelper.ADD_SUCCESS();
    }

    public ApiResult delete(Long id) {
        service.select().eq("id", id).end().delete();
        return ApiHelper.DEL_SUCCESS();
    }

    public ApiResult edit(Long id, P param) {
        service.select().eq("id", id).end().replace(param);
        return ApiHelper.PUT_SUCCESS();
    }

    public ApiResult all(P param) {
        Map<String, Object> map = BeanUtil.beanToMap(param);
        map.remove("page");
        map.remove("limit");
        for (String key : map.keySet()) {
            Object value = map.get(key);
            if (value == null) continue;
            String type = value.getClass().getSimpleName();
            key = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, key);
            switch (type) {
                case "Integer":
                    service.select().eq(key, value);
                    break;
                case "String":
                    String valueStr = value.toString();
                    String[] dateRange = valueStr.split(separator, 2);
                    if (dateRange.length == 2 && !dateRange[0].equals(dateRange[1])) {
                        service.select().between(key, dateRange[0], dateRange[1]);
                    } else {
                        service.select().likeRight(key, dateRange[0]);
                    }
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + type);
            }
        }
        return ApiHelper.PAGE_SUCCESS(service.pageMap());
    }

    public ApiResult detail(Long id) {
        return ApiHelper.GET_SUCCESS(
                service.select().eq("id", id).end().find()
        );
    }

}
